import { defineStore } from 'pinia'
import { ref, watchEffect } from 'vue';
import { mySchoolRule, mySendTimeRule, myTipsMoneyRule, objectAny, PackCategoriesRule } from '../options/base';
import { computedTime } from '../utils/time';
import { showModal } from '../utils/utils';


const clientUserMG = uniCloud.importObject('client-user-manage', { customUI: true })
const publicManage = uniCloud.importObject(`admin-public-manage`, { customUI: true })

const db = uniCloud.database()

export type userInfoRule = {
	mobile : string;
	nickname : string;
	toDayOrder : number;
	toDayUseMoney : string;
	toTalOrder : number
	toTalUseMoney : string
	_id : string;
	avatarUrl : string
}

export const myUserStore = defineStore(`user`, () => {
	const myUser = ref<userInfoRule>({
		_id: ``, //用户ID
		mobile: ``,
		nickname: ``,
		toDayOrder: 0,		// 今日订单,
		toTalOrder: 0,		//合计订单，
		toDayUseMoney: `0.00`,		//今日消费
		toTalUseMoney: `0.00`,		//合计消费
		avatarUrl: uni.getStorageSync(`wxAvatarUrl`) || ``,       // 用户头像地址
	});

	async function getMyUserInfo() : Promise<userInfoRule> {
		const schoolStore = mySchoolStore()
		const schoolId = schoolStore.mySchool._id;

		const token = uni.getStorageSync(`uni_id_token`);
		if (token == null) {
			return myUser.value
		}

		const { myErrCode, errMsg, data } = await clientUserMG.getUserInfo(schoolId);
		if (myErrCode === 0) {
			if (data.avatarUrl == null || data.avatarUrl == '') {
				data.avatarUrl = uni.getStorageSync(`wxAvatarUrl`) || ``    //加上本地授权后的头像
			}
			myUser.value = data;
		}
		return myUser.value

	}

	return {
		myUser,
		getMyUserInfo,
	}
})

export const myConfigStore = defineStore(`config`, () => {

	const myConfig = ref({});

	const getMyConfig = async (schoolId : string) => {
		try {
			const { data, myErrCode, errMsg } = await publicManage.getSystemConfig(schoolId);
			if (myErrCode !== 0) {
				showModal({
					title: `异常提示`,
					content: errMsg,
					showCancel: false
				})
				return {}
			}
			myConfig.value = data;
			return {
				keyVaule: data
			}
		} catch (error) {
			console.log(error);
			showModal({
				content: `获取系统配置异常，请稍后再试`,
				title: `异常提示`,
				showCancel: false
			})
		}
		return {}
	}

	return {
		myConfig,
		getMyConfig
	}

})


export const mySchoolStore = defineStore('school', () => {

	const mySchool_cache = uni.getStorageSync(`mySchool`);
	let defaultSchool : mySchoolRule = {
		school_name: `默认一统云校`,
		_id: ``,
		city_code: ``,
		enable_status: true,
		description: ``,
		city_id_array: []
	}

	if (mySchool_cache != null && mySchool_cache != ``) {
		try {
			defaultSchool = JSON.parse(mySchool_cache);
		} catch (error) {
			console.log(`转换本地学校数据失败，失败原因：` + error);
		}

	}
	const mySchool = ref(defaultSchool);

	watchEffect(() => {
		console.log(`======> 学校发生了变化，开始请求学校的相关配置 <======`)
		const schoolId = mySchool.value._id;
		if (schoolId.trim() === '') {
			return console.log(`xxxxxx=> 学校ID为空，无需获取该学校的配置信息  <=xxxxxx`)
		}
		myConfigStore().getMyConfig(schoolId);
	})

	const setMySchool = (school : any) => {
		uni.setStorageSync('mySchool', JSON.stringify(school));
		mySchool.value = school
	}

	return {
		mySchool,
		setMySchool
	}

})


export const mySendTimeStore = defineStore(`sendTime`, () => {
	const mySendTime = ref<Array<mySendTimeRule>>([]);

	const getSendTime = async (schoolId : string) => {
		try {
			const { result: { data } } = await db
				.collection(`admin-send-time`)
				.where({
					// school_id: db.command.eq(schoolId).or(db.command.eq('')),
					enable: true
				})
				.get();

			const list = data.map((it : any) => {
				const {
					alias_name,
					name,
					start_time_ms,
					end_time_ms,
					formatTimeList
				} = computedTime(it);

				it.alias_name = alias_name;
				it.name = name;
				it.start_time = start_time_ms;
				it.end_time = end_time_ms;
				it.splice_time_text = formatTimeList;

				return it;

			}).filter((it : any) => it.splice_time_text.length > 0);

			mySendTime.value = list;
			return list
		} catch (error) {
			console.log(error);
			showModal({
				content: `获取派送时间异常，请稍后再试`,
				title: `异常提示`,
				showCancel: false
			})
		}

		return []
	}

	return {
		mySendTime,
		getSendTime
	}
})

export const myTipsMoneyStore = defineStore(`tipsMoney`, () => {
	const myTipsMoney = ref<Array<myTipsMoneyRule>>([]);

	const getTipsMoney = async (schoolId : string) => {
		try {
			const { result: { data } } = await db
				.collection(`admin-tips-money`)
				.where({
					school_id: db.command.eq(schoolId).or(db.command.eq('')),
					enable: true
				})
				.get();
			myTipsMoney.value = data;
			return data
		} catch (error) {
			console.log(error);
			showModal({
				content: `获取小费列表异常，请稍后再试`,
				title: `异常提示`,
				showCancel: false
			})
		}
		return []
	}

	return {
		myTipsMoney,
		getTipsMoney
	}
})

export const myPackCategoriesStore = defineStore(`packCategories`, () => {
	let getStatus : `init` | `pending` | `fulfilled` | `rejected` = `init`;
	const packToggle = ref({
		0: `小物件`,
		1: `中物件`,
		2: `大物件`,
		3: `超大物件`
	});
	const myPackCategories = ref<PackCategoriesRule>([]);

	const getPackCategories = async (school_id : string) => {
		getStatus = `pending`
		try {
			const { result: { data } } = await db
				.collection(`admin-pack-categories`)
				.where({
					// school_id: db.command.eq(school_id).or(db.command.eq('')),
					enable: true
				})
				.get();
			myPackCategories.value = data;
			getStatus = `fulfilled`
			return data;
		} catch (error) {
			getStatus = `rejected`

			console.log(error);
			showModal({
				content: `获取物件分类异常，请稍后再试`,
				title: `异常提示`,
				showCancel: false
			})
		}
		return []
	}

	const packTypeToStr = (pack_type : 0 | 1 | 2 | 3) => {
		return packToggle.value[pack_type]
	}

	const idFindPack = async (id : string) => {
		if (getStatus === `init` || getStatus === `pending`) {
			const { _id } = mySchoolStore().mySchool
			await getPackCategories(_id);
		}
		const packs = myPackCategories.value;
		for (let i = 0; i < packs.length; i++) {
			if (packs[i]._id === id) {
				return packs[i];
			}
		}
		return {}
	}

	return {
		packToggle,
		getStatus,
		myPackCategories,
		getPackCategories,
		idFindPack,
		packTypeToStr
	}

})